package com.boot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;

/**
 * @EnableWebSecurity:SpringSecurity的配置类 开启SpringSecurity【自带大量过滤器链:责任链模式】
 */
@Configuration //
@EnableWebSecurity //5.x中@EnableWebSecurity自带@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http.authorizeHttpRequests(authorizeHttpRequests -> //在这个后面开始配置URL相关的【URL访问权限控制相关的】
                        authorizeHttpRequests
                                /*.requestMatchers("/login").permitAll() *///permitAll:授予所有权限【匿名可以访问的、不用登录就可以访问】,这是不需要因为formLogin定义了
                                .anyRequest() //任何的请求
                                .authenticated() //需要认证【登录】后才能访问
                )

                .formLogin(formLogin -> formLogin.loginPage("/login") //登录页面
                        .loginProcessingUrl("/login").permitAll() //登录接口可以匿名访问
                        .defaultSuccessUrl("/index") //登录成功访问/index页面
                )
                .csrf(AbstractHttpConfigurer::disable) //关闭
                .logout(logout -> logout.deleteCookies("JSESSIONID").invalidateHttpSession(true).logoutSuccessUrl("/index")) //退出登录接口
                .build();
    }
}
